﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Get;
using Traceability.App.Api.DTO;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Get
{
    public class GetTraceabilityDescHandler : IRequestHandler<GetTraceabilityDescCommand, ApiPaging<TraceabilityDTO>>
    {
        private readonly IBaseRepository<TraceabilityModel> traceabilityRepo;
        
        private readonly IBaseRepository<ProductModel> productRepo;

        public GetTraceabilityDescHandler(IBaseRepository<TraceabilityModel> traceabilityRepo,IBaseRepository<ProductModel> productRepo) 
        {
            this.traceabilityRepo = traceabilityRepo;
            
            this.productRepo = productRepo;
        }
        public Task<ApiPaging<TraceabilityDTO>> Handle(GetTraceabilityDescCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<TraceabilityDTO> res = new ApiPaging<TraceabilityDTO>();
            var product = productRepo.GetAll().Where(x => x.IsDelete == false);
            var traceability = traceabilityRepo.GetAll().Where(x => x.IsDelete == false && x.Batch==request.Batch);
            var dto = from a in traceability
                      join b in product on a.Pid equals b.Id
                      select new TraceabilityDTO
                      {
                          Id = a.Id,
                          Batch = a.Batch,
                          CreateName = a.CreateName,
                          CreateTime = a.CreateTime,
                          ProductName = b.ProductName,
                          UpdateName = a.UpdateName,
                          ExpirationDate = a.ExpirationDate,
                          Information_Completeness = a.Information_Completeness,
                          Manufacturers = a.Manufacturers,
                          Pid = a.Pid,
                          ProduceCode = a.ProduceCode,
                          UpdateTime = a.UpdateTime,
                          Photo=a.Photo,
                      };
            res.TotalCount = dto.Count();
            res.TotalPage = (int)Math.Ceiling((res.TotalCount * 1.0) / request.PageSize);
            res.Datas = dto.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            res.Msg = "查询成功";
            return Task.FromResult(res);
        }
    }
}
